// import TopHeader from "../Home/TopHeader";
import { getClientId, getWebId, logout } from "@/common/auth/token";
import { dispatchPubsub } from "@/hy_dev_lib/src/store";
import * as signalR from "@microsoft/signalr";

export const startSignalRConnection = async (
  connection: signalR.HubConnection,
  userId: string
) => {
  try {
    await connection.start();
    const WebId = getWebId();
    const ClientId = getClientId();
    // console.log("userId", userId)
    // console.log("WebId", WebId)
    // console.log("ClientId", ClientId)
    // console.log(12, WebId, userInfoData)
    connection
      .invoke("login", { Name: userId, WebId, Clientid: ClientId })
      .then((res) => {
        console.log("SignalR 注入成功");
      })
      .catch((error) => {
        console.log("注入失败" + error);
      });
    //console.log('SignalR connection established');
  } catch (err) {
    setTimeout(() => startSignalRConnection(connection, userId), 5000);
  }
};

export const stopSignalRConnection = async (
  connection: signalR.HubConnection
) => {
  await connection.stop();
};

export const setupSignalRConnection = (userId: string) => {
  //"http://localhost:9235/";
  //"http://localhost:9235"
  const connection = new signalR.HubConnectionBuilder()
    .withUrl(SYSTEM_GLOBAL.signalRUrl + "chatHub")
    // .withUrl("http://" + surls + "/chatHub")
    .withAutomaticReconnect()
    .withHubProtocol(new signalR.JsonHubProtocol())
    .configureLogging(signalR.LogLevel.Information)
    .build();

  connection.serverTimeoutInMilliseconds = 60000;

  connection.onclose((error) => {});

  connection.onreconnecting((error) => {});

  connection.onreconnected((connectionId) => {});

  startSignalRConnection(connection, userId);

  // connection.on("send", data => {
  //   console.log(data, "send");
  // });
  connection.on("iswhere", (res) => {
    dispatchPubsub("SHOW_TIPS_MODAL", {
      content: `您的账号已在其他设备登录`,
      inoperable: true,
      type: "error",
      okText: "确定",
      callback: async () => {
        logout();
      },
    });
  });
  connection.on("iswhere2", (res) => {
    dispatchPubsub("SHOW_TIPS_MODAL", {
      content: `已存在其他账号登录`,
      inoperable: true,
      type: "error",
      okText: "确定",
      callback: async () => {
        logout();
      },
    });
  });
  return connection;
};
